<template>
  <el-form label-width="100px" :model="spuInfo" :rules="spuRules" ref="spuFormRef">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
        <el-option
          v-for="trademark in trademarkList"
          :key="trademark.id"
          :label="trademark.tmName"
          :value="trademark.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" :rows="4" v-model="spuInfo.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload
        v-model:file-list="spuInfo.spuImageList"
        :action="`${BASE_URL}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select
        :placeholder="`还剩下${filterSpuSaleAttrList.length}个未选择`"
        v-model="spuInfo.spuSaleAttr"
      >
        <el-option
          v-for="baseSaleAttr in filterSpuSaleAttrList"
          :key="baseSaleAttr.id"
          :label="baseSaleAttr.name"
          :value="baseSaleAttr.name"
        />
      </el-select>
      <el-button type="primary" @click="addBaseSaleAttr" :disabled="!spuInfo.spuSaleAttr"
        >添加销售属性</el-button
      >
      <el-table border :data="spuInfo.spuSaleAttrList" style="margin-top: 20px">
        <el-table-column
          label="序号"
          width="80px"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性名"
          prop="saleAttrName"
          width="100px"
        ></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row, $index }">
            <el-tag
              v-for="tag in row.spuSaleAttrValueList"
              :key="tag"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="handleClose(row, tag)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput(row)"
            >
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template v-slot="{ row, $index }">
            <el-button type="danger" :icon="Delete" @click="deleteAttr"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitSpuForm(spuFormRef)">保存</el-button>
      <el-button @click="emits('changeValue', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed, nextTick } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqGetAllTrademarkList,
  reqGetBaseSaleAttrList,
  reqSaveSpuInfo,
  reqUpdateSpuInfo,
  reqGetSpuImageList,
  reqGetSpuSaleAttrList,
} from "@/api/product/spu";
import { ElMessage, ElInput } from "element-plus";
import { useCategoryStore } from "@/stores/categoryList";
import { filterFields } from "element-plus/es/components/form/src/utils";
import type { UploadProps, UploadUserFile, FormInstance, FormRules } from "element-plus";
const formSize = ref("default");
const spuFormRef = ref<FormInstance>();
const emits = defineEmits(["changeValue"]);
const props = defineProps(["SpuInfo"]);

const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
//创建stores对象
const categoryStore = useCategoryStore();

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 动态读取环境变量中的值
const BASE_URL = import.meta.env.VITE_API_URL;

//定义发送请求所需参数格式
// 定义一个存储spu相关数据的变量
const spuInfo = reactive({
  spuName: "", // spu的名称
  tmId: "", // spu品牌
  description: "", // spu描述
  spuImageList: [], // 存储spu图片的数组
  spuSaleAttrList: [], // 基本销售属性
  spuSaleAttr: "", // 收集选中的属性 颜色 版本  尺寸
  category3Id: "", // 三级id

  ...props.SpuInfo, //解构后将前面的属性进行覆盖
});

// 接收前七个球回来的两个下拉框数组
const trademarkList = ref([]);
const baseSaleAttrList = ref([]); //

// 添加校验规则
const spuRules = reactive<FormRules>({
  spuName: [
    { required: true, message: "请输入SPU名称", trigger: "blur" },
    { min: 1, max: 10, message: "SPU名称在1-10个字符之间", trigger: "blur" },
  ],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [
    {
      required: true,
      message: "请选择一张图片",
      type: "array",
      trigger: "change",
    },
  ],
  spuSaleAttrList: [
    {
      required: true,
      message: "请至少添加一个属性",
      type: "array",
      trigger: "click",
    },
  ],
});

// 提交前的校验
const submitSpuForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 再判断一下，基础销售是不是有属性值，如果有一项无值 不能提交
      const spuSaleAttrList = spuInfo.spuSaleAttrList;
      if (
        spuSaleAttrList.length &&
        !spuSaleAttrList.every((item) => item.spuSaleAttrValueList.length)
      ) {
        ElMessage.error("有属性值为空，请添加...");
        return; // 不要添加了
      }

      // 给存放照片数组去重
      spuInfo.spuImageList = spuInfo.spuImageList.map((item) => {
        return {
          imgName: item.name as string,
          imgUrl: item.response?.data || item.url,
        };
      });
      // 获取三级导航id
      spuInfo.category3Id = categoryStore.category3Id;
      // await reqSaveSpuInfo(spuInfo);
      if (spuInfo.id) {
        // 此时是更新操作
        await reqUpdateSpuInfo(spuInfo);
      } else {
        // 才是真正的添加spuInfo
        await reqSaveSpuInfo(spuInfo);
      }

      ElMessage.success("spu添加成功...");

      emits("changeValue", 1);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 图片删除
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
  // 第二个参数时删除照片后装剩余照片的数组
  spuInfo.spuImageList = uploadFiles;
};
// 图片预览
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 图片上传陈宫
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log("图片上传成功之后执行");
  //  spuInfo.spuImageList.push({
  //   imgName: uploadFile.name,
  //   imgUrl: response.data,
  // });

  spuInfo.spuImageList = uploadFiles;

  // 清除校验规则
  spuFormRef.value!.clearValidate(["spuImageList"]);

  // console.log(response, uploadFile);
};

// 上传之前的图片格式校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgTypes = ["image/jpeg", "image/jpg", "image/png"];

  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片的格式只能是jpg/png/jepg,请重新选择");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("只能上传大小小于2M大小的图片");
    return false;
  }
  return true;
};

// 添加销售属性
const addBaseSaleAttr = () => {
  const spuSaleAttrList = spuInfo.spuSaleAttrList;
  if (
    spuSaleAttrList.length &&
    spuSaleAttrList.some((item: any) => item.spuSaleAttrValueList.length == 0)
  ) {
    ElMessage.error("属性值不能为空,请添加...");
    return; // 不要向下执行  也就是不要添加新的属性
  }
  // 因为要根据是否他有id来判断是添加还是修改
  const id = baseSaleAttrList.value!.find((item) => item.name == spuInfo.spuSaleAttr).id;
  spuInfo.spuSaleAttrList.push({
    baseSaleAttrId: id,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],
    // 传递对象时让输入框默认消失
    inputVisible: false,
  });

  // 清空下拉框数
  spuInfo.spuSaleAttr = "";
};

// 实现计算属性 数组中属性名称的计算
const filterSpuSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseSale) => {
    return !spuInfo.spuSaleAttrList.find((item) => baseSale.name == item.saleAttrName);
  });
});

// 删除属性值函数
const handleClose = (row: any, tag: any) => {
  // 找到当前属性在数组中下标
  let index = row.spuSaleAttrValueList.indexOf(tag);
  // 根据下表删除数组中的属性值
  row.spuSaleAttrValueList.splice(index, 1);
};
// 输入框函数
const showInput = (row: any) => {
  row.inputVisible = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
// 将输入的值添加到数组中显示tag
const handleInputConfirm = (row: any) => {
  if (inputValue.value) {
    const spuSaleAttrValueList = row.spuSaleAttrValueList;
    if (
      spuSaleAttrValueList.length &&
      spuSaleAttrValueList.find(
        (item: any) => item.saleAttrValueName === inputValue.value
      )
    ) {
      ElMessage.error("属性值不能重复,请更换一个");
      // inputVisible.value = false
      row.inputVisible = false;
      inputValue.value = "";
      return; // 不要向下执行了 也就是不要再添加属性了
    }
    const id = baseSaleAttrList.value.find((item: any) => item.name === row.saleAttrName)
      .id;
    // dynamicTags.value.push(inputValue.value)
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: id,
      saleAttrName: row.saleAttrName, // 当前属性名称 比如 颜色 版本 尺寸
      saleAttrValueName: inputValue.value, // 具体的属性值
    });
  }
  row.inputVisible = false;
  inputValue.value = "";
};

// 8. 删除销售属性
const deleteAttr = (row: any, index: number) => {
  spuInfo.spuSaleAttrList.splice(index, 1);
};

// 点击修改按钮实现数据回显

// 当组件挂载时触发,获取两个下拉框数据
onMounted(async () => {
  // 判断此时的spuInfo是否有id,如果有就是修改操作,如果没有就是添加操作
  try {
    let { id } = spuInfo;
    // console.log("xiugzjsdfhgvoeasngiobso", id);

    let promise = [reqGetAllTrademarkList(), reqGetBaseSaleAttrList()];
    if (id) {
      promise = promise.concat([reqGetSpuImageList(id), reqGetSpuSaleAttrList(id)]);
    }
    let [
      TrademarkList,
      BaseSaleAttrList,
      resSpuImageList,
      resSpuSaleAttrList,
    ] = await Promise.all(promise);

    // const [TrademarkList, BaseSaleAttrList] = await Promise.all([]);
    // 将请求结果保存到变量上
    trademarkList.value = TrademarkList;
    baseSaleAttrList.value = BaseSaleAttrList;
    // 请求发送成功获取图片列表和属性列表数组值
    if (resSpuImageList && resSpuSaleAttrList) {
      spuInfo.spuImageList = resSpuImageList.map((item: any) => {
        return {
          ...item,
          url: item.imgUrl,
          name: item.imgName,
        };
      });
      spuInfo.spuSaleAttrList = resSpuSaleAttrList;
    }

    //
    // console.log("商品名称", trademarkList.value);
    // console.log("销售属性", baseSaleAttrList.value);
  } catch (error) {
    ElMessage.error("请求下拉框数据失败");
  }
});
</script>
<style></style>
